package com.luyi.sensor.config;

import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * GlobalExceptionInterceptor全局异常拦截
 * author: luyi
 * time: 2022/1/8 20:55
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionInterceptor {

    @ExceptionHandler(value=Exception.class)
    public Result exceptionHandler(HttpServletRequest request, Exception e) {
        String failMsg = null;

        if(e instanceof MethodArgumentNotValidException) {
            // 拿到参数校验具体异常信息提示
            failMsg =((MethodArgumentNotValidException) e).getBindingResult().getFieldError().getDefaultMessage();
            System.out.println(failMsg);

//            result.setCode();


            System.out.println();
        }

        return Result.error("-1", e.getMessage());//直接吐回给前端, failMsg
    }
}
